import React, { useEffect, useRef, useState } from 'react';
import {
  Button,
  Tag,
  Space,
  Card,
  Empty,
  Select,
  Spin,
  Breadcrumb,
} from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProCard, { StatisticCard } from '@ant-design/pro-card';
import ProLayout, {
  PageContainer,
  SettingDrawer,
} from '@ant-design/pro-layout';
import { useRequest } from 'umi';
import CompareChart from './component/CompareChart';
import TeamColumChart from './component/TeamColumChart';
import PieChart from './component/PieChart';
import DemoLine from './component/LineChart';

const { Option } = Select;
const { Statistic, Divider } = StatisticCard;

export default (props: any) => {
  const actionRef = useRef<ActionType>();

  const [teamList, setTeamList] = useState<any>(); //团队下拉框
  const [firstTeam, setFirstTeam] = useState<any>(); //选中的第一个团队
  const [secondTeam, setSecondTeam] = useState<any>(); //选中的第二个团队
  const [chartData, setChartData] = useState<any>(false);

  const [boardData, setBoardData] = useState<any>(); //返回的原始数据
  const [compareData, setCompareData] = useState<any>(); //用于对比图完备数据
  const [pieData, setPieData] = useState<any>(); //用于饼图的完备数据
  const [lineData, setLineData] = useState<any>(); //用于时间曲线的完备数据

  const [directionList, setDirectionList] = useState<any>(); //方向下拉框
  const [directionName, setDirectionName] = useState(); //选中的方向名称

  const [directionFlag, setDirectionFlag] = useState(false);

  const [tableNameForLine, setTableNameForLine] = useState('论文'); //曲线选中的成果类型
  const [tabelNameListForLine, setTableNameListForLine] = useState([
    '论文',
    '专著',
    '专利',
    '纵向项目',
    '横向项目',
  ]); //曲线的成果类型下拉框

  const [tableName, setTableName] = useState('论文'); //饼状图选中的成果类型
  const [tabelNameList, setTableNameList] = useState([
    '论文',
    '专著',
    '专利',
    '奖励',
    '纵向项目',
    '横向项目',
    '成果转换',
  ]); //饼状图的成果类型下拉框

  //方向看板
  const getDirectionBoard = useRequest(
    (directionId = null) => {
      return {
        url: `http://10.1.40.84:9993/board/getDirectionBoard?directionId=${directionId}`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
    },
  );

  //个人信息
  const getUserInfo = useRequest((data = null) => {
    return {
      url: `http://10.1.40.84:9993/user/getUserInfo`,
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data,
    };
  });

  //返回团队下拉框
  const getGroupLabel = useRequest(
    (directionId = '') => {
      return {
        url: `http://10.1.40.84:9993/group/getGroupLabel?level=${directionId}`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
    },
  );

  //封装对比柱状图
  const convertCompareData = (
    firstTeamName: string,
    secondTeamName: string,
    allData: any,
  ) => {
    var temp: any = [];
    if (allData) {
      console.log(firstTeamName, secondTeamName, allData);
      tabelNameList.map((t: any) => {
        var firstItem: any, secondItem: any;
        allData.map((a: any) => {
          if (a.groupName === firstTeamName && a.key === t) {
            firstItem = a;
          }
          if (a.groupName === secondTeamName && a.key === t) {
            secondItem = a;
          }
        });
        console.log(firstItem, secondItem, t);
        var item: any = {};
        item[firstTeamName] = firstItem?.value || 0;
        item[secondTeamName] = secondItem?.value || 0;
        item['tableName'] = t;
        temp.push(item);
      });
    }

    return temp;
  };

  //封装饼状图
  const convertPieData = (tableNameSelect: string, allData: any) => {
    var temp: any = [];
    if (allData) {
      temp = allData.filter((e: any) => e.key === tableNameSelect && e.value);
    }
    return temp;
  };

  //封装时间曲线图
  const convertLineData = (tableNameSelect: string, allData: any) => {
    var temp: any = [];
    if (allData) {
      temp = allData
        .filter((e: any) => e.tableName === tableNameSelect)
        .sort((a: any, b: any) => parseInt(a.year) - parseInt(b.year));
    }
    return temp;
  };

  useEffect(() => {
    if (props.directionId) {
      getDirectionBoard.run(props.directionId).then((board) => {
        setBoardData(board);
        setChartData(board.chart);
        setPieData(convertPieData(tableName, board?.groupMap));
        setLineData(convertLineData(tableNameForLine, board?.yearMap));
        getGroupLabel.run(props.directionId).then((data) => {
          setTeamList(data);
          setDirectionFlag(!directionFlag);
          if (data.length > 1) {
            setFirstTeam(data[0].label);
            setSecondTeam(data[1].label);
            setCompareData(
              convertCompareData(data[0].label, data[1].label, board?.groupMap),
            );
          } else if (data.length == 1) {
            setFirstTeam(data[0].label);
            setSecondTeam(data[0].label);
            setCompareData(
              convertCompareData(data[0].label, data[0].label, board?.groupMap),
            );
          } else {
            setFirstTeam('');
            setSecondTeam('');
            setCompareData([]);
          }
        });
      });
    }
  }, [props.directionId]);

  useEffect(() => {
    boardData?.groupMap && firstTeam && secondTeam
      ? setCompareData(
          convertCompareData(firstTeam, secondTeam, boardData.groupMap),
        )
      : '';
  }, [firstTeam, secondTeam]);

  useEffect(() => {
    tableName && boardData?.groupMap
      ? setPieData(convertPieData(tableName, boardData?.groupMap))
      : '';
  }, [tableName]);

  useEffect(() => {
    tableNameForLine && boardData?.yearMap
      ? setLineData(convertLineData(tableNameForLine, boardData?.yearMap))
      : '';
  }, [tableNameForLine]);

  return props.directionId ? (
    <Spin spinning={getDirectionBoard.loading}>
      <ProCard title="方向总体概况" split={'vertical'} headerBordered bordered>
        <ProCard split="horizontal" colSpan={24}>
          <ProCard split="vertical">
            <StatisticCard
              statistic={{
                title: '论文数量',
                value: chartData?.paper,
              }}
            />
            <StatisticCard
              statistic={{
                title: '纵向项目数量',
                value:
                  (chartData?.vertProject?.overcount || '0') +
                  '/' +
                  (chartData?.vertProject?.undercount || '0'),
                description: (
                  <Statistic
                    title="到账"
                    value={chartData?.vertProject?.money}
                    suffix={'万元'}
                    valueStyle={{ color: 'red' }}
                  />
                ),
              }}
            />
            <StatisticCard
              statistic={{
                title: '横向项目数量',
                value:
                  chartData?.horProject?.overcount ||
                  '0' + '/' + (chartData?.horProject?.undercount || '0'),
                description: (
                  <Statistic
                    title="到账"
                    value={chartData?.horProject?.money}
                    suffix={'万元'}
                    valueStyle={{ color: 'red' }}
                  />
                ),
              }}
            />
            <StatisticCard
              statistic={{
                title: '国际合作项目数数量',
                value: 0 + '/' + 0,
                description: (
                  <Statistic
                    title="到账"
                    value={0}
                    suffix={'万元'}
                    valueStyle={{ color: 'red' }}
                  />
                ),
              }}
            />
            <StatisticCard
              statistic={{
                title: '软件著作',
                value: chartData.softwareCopyright,
              }}
            />
          </ProCard>
          <ProCard split="vertical">
            <StatisticCard
              statistic={{
                title: '专著',
                value: chartData?.book,
                suffix: '',
              }}
            />
            <StatisticCard
              statistic={{
                title: '制定标准',
                value: 0,
                suffix: '',
              }}
            />
            <StatisticCard
              statistic={{
                title: '获得奖项',
                value: chartData?.reward,
                suffix: '',
              }}
            />
            <StatisticCard
              statistic={{
                title: '申请专利',
                value: chartData?.patent,
                suffix: '',
              }}
            />
            <StatisticCard
              statistic={{
                title: '授权专利',
                value: chartData?.grantPatent,
                suffix: '',
              }}
            />
          </ProCard>
          <ProCard split="vertical">
            <StatisticCard
              statistic={{
                title: '人才称号',
                value: (chartData.省部级 || 0) + (chartData.国家级 || 0),
                description: (
                  <Space>
                    <Statistic
                      title="省部级"
                      value={chartData.省部级 || 0}
                      suffix={''}
                      valueStyle={{ color: 'red' }}
                    />
                    <Statistic
                      title="国家级"
                      value={chartData.国家级 || 0}
                      suffix={''}
                      valueStyle={{ color: 'red' }}
                    />
                  </Space>
                ),
              }}
            />
            <StatisticCard
              statistic={{
                title: '仪器设备研制',
                value: chartData.equipmentDevelop,
                suffix: '',
              }}
            />

            <StatisticCard
              statistic={{
                title: '成果转化',
                value: chartData.achieveTrans,
                suffix: '',
              }}
            />
            <StatisticCard
              statistic={{
                title: '年度标志性成果',
                value: chartData.yearProject,
                suffix: '',
              }}
            />
            <StatisticCard
              statistic={{
                title: '其他标志性成果',
                value: chartData.other,
                suffix: '',
              }}
            />
          </ProCard>
        </ProCard>
      </ProCard>
      <Divider />

      <ProCard
        title="方向成果时间分布"
        extra={
          <Space>
            <span>选择成果类型：</span>
            <Select
              defaultValue={tableNameForLine}
              style={{ width: 120 }}
              onChange={(e) => {
                setTableNameForLine(e);
              }}
            >
              {tabelNameListForLine.map((e) => (
                <Option key={e} value={e}>
                  {e}
                </Option>
              ))}
            </Select>
          </Space>
        }
        style={{ height: 320 }}
      >
        <DemoLine data={lineData} xField={'year'} yField={'count'} />
      </ProCard>

      <Divider />
      <ProCard split={'vertical'}>
        <ProCard split={'horizontal'} colSpan="65%">
          <ProCard title="方向科研成果">
            <TeamColumChart
              data={boardData?.groupMap}
              xField={'groupName'}
              yField={'value'}
              seriesField={'key'}
            />
          </ProCard>
        </ProCard>
        <ProCard split={'horizontal'} colSpan="35%">
          <ProCard
            title="成果占比"
            extra={
              <Space>
                <span>选择成果类型：</span>
                <Select
                  defaultValue={tableName}
                  style={{ width: 120 }}
                  onChange={(e) => {
                    setTableName(e);
                  }}
                >
                  {tabelNameList.map((e) => (
                    <Option key={e} value={e}>
                      {e}
                    </Option>
                  ))}
                </Select>
              </Space>
            }
          >
            <PieChart
              data={pieData}
              angleField={'value'}
              colorField={'groupName'}
            />
          </ProCard>
        </ProCard>
      </ProCard>

      {/* <ProCard split="vertical">
      <ProCard title={'方向科研成果'}>
        <TeamColumChart />
      </ProCard>
    </ProCard> */}

      <Divider />
      <ProCard split="vertical">
        {boardData && teamList ? (
          <ProCard
            title={'各团队科研成果'}
            extra={
              directionFlag ? (
                <Space>
                  <span>左侧团队：</span>
                  <Select
                    style={{ width: 360 }}
                    onChange={(value) => {
                      setFirstTeam(value);
                    }}
                    defaultValue={teamList[0]?.label || ''}
                  >
                    {teamList?.map((e: any) => (
                      <Option value={e.label} key={e.label}>
                        {e.label}
                      </Option>
                    ))}
                  </Select>
                  <span>右侧团队：</span>
                  <Select
                    style={{ width: 360 }}
                    onChange={(value) => {
                      setSecondTeam(value);
                    }}
                    defaultValue={teamList[1]?.label || ''}
                  >
                    {teamList?.map((e: any) => (
                      <Option value={e.label} key={e.label}>
                        {e.label}
                      </Option>
                    ))}
                  </Select>
                </Space>
              ) : (
                <Space>
                  <span>左侧团队：</span>
                  <Select
                    style={{ width: 360 }}
                    onChange={(value) => {
                      setFirstTeam(value);
                    }}
                    defaultValue={teamList[0]?.label || ''}
                  >
                    {teamList?.map((e: any) => (
                      <Option value={e.label} key={e.label}>
                        {e.label}
                      </Option>
                    ))}
                  </Select>
                  <span>右侧团队：</span>
                  <Select
                    style={{ width: 360 }}
                    onChange={(value) => {
                      setSecondTeam(value);
                    }}
                    defaultValue={teamList[1]?.label || ''}
                  >
                    {teamList?.map((e: any) => (
                      <Option value={e.label} key={e.label}>
                        {e.label}
                      </Option>
                    ))}
                  </Select>
                </Space>
              )
            }
          >
            <CompareChart
              data={compareData}
              xField={'tableName'}
              yField={[firstTeam, secondTeam]}
            />
          </ProCard>
        ) : (
          ''
        )}
      </ProCard>
      <Divider />
    </Spin>
  ) : (
    <ProCard>
      <div style={{ height: 260 }}></div>
      <Divider />
      <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
      <Divider />
      <div style={{ height: 260 }}></div>
    </ProCard>
  );
};
